package com.imooc.spark.streaming.app

import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.SparkConf
import org.apache.spark.streaming.{Seconds, StreamingContext}
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe
import org.apache.spark.streaming.kafka010.KafkaUtils
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent

/**
  * @description Spark Streaming整合Flume、Kafka实现日志的实时微批处理
  * @author yuyon26@126.com
  * @date 2018/10/30 11:16
  */
object FlumeKafkaStreamingUserAgentApp {
  def main(args: Array[String]): Unit = {

    if (args.length != 3) {
      System.err.println("Usage: KafkaStreamingWordCountTest <bootstrapServers> <groupId> <topics>")
      System.exit(1)
    }

    val sparkConf = new SparkConf().setMaster("local[2]").setAppName("FlumeKafkaStreamingUserAgentApp")
    val ssc = new StreamingContext(sparkConf, Seconds(5))
    ssc.sparkContext.setLogLevel("ERROR")

    val Array(bootstrapServers, groupId, topics) = args

    val kafkaParams = Map[String, Object](
      "bootstrap.servers" -> bootstrapServers,
      "key.deserializer" -> classOf[StringDeserializer],
      "value.deserializer" -> classOf[StringDeserializer],
      "group.id" -> groupId,
      "auto.offset.reset" -> "latest",
      "enable.auto.commit" -> (false: java.lang.Boolean)
    )

    val message = KafkaUtils.createDirectStream[String, String](
      ssc,
      PreferConsistent,
      Subscribe[String, String](topics.split(",").toArray, kafkaParams)
    )

    //TODO:业务逻辑
    message.map(record => record.value()).print()

    ssc.start()
    ssc.awaitTermination()
  }
}
